package net.simo.servicebook.controller.login;

import java.io.IOException;
import java.io.Serializable;

import javax.enterprise.context.Conversation;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.Produces;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import net.simo.servicebook.model.security.Role;
import net.simo.servicebook.model.security.User;
import net.simo.servicebook.service.UserManager;

@SessionScoped
@Named
public class Login implements Serializable {
	private static final long serialVersionUID = -1937395565447050546L;

	@Inject
	private UserManager userManager;
	@Inject
	private Credentials credentials;
	private User currentUser;
	@Inject
	private Conversation conversation;

	public void login() {
		currentUser = userManager.findUser(credentials.getEmail(),
				credentials.getPassword());
		if (currentUser != null) {
			FacesContext.getCurrentInstance().addMessage(null,
					new FacesMessage("Welcome, " + currentUser.getUserName()));
			try {
				FacesContext.getCurrentInstance().getExternalContext()
						.redirect("index.jsf");
			} catch (IOException e) {
				e.printStackTrace();
			}

		} else {
			FacesContext.getCurrentInstance().addMessage(null,
					new FacesMessage("User not found"));
		}
	}

	public void logout() {
		currentUser = null;
		
		if (conversation.getId() != null) {
			conversation.end();
		}
		try {
			FacesContext.getCurrentInstance().getExternalContext()
					.redirect("index.jsf");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public boolean isLoggedIn() {
		return currentUser != null;
	}

	public boolean isAdmin() {
		if (isLoggedIn()) {
			return Role.ROLE_ADMIN.equals(currentUser.getRole().getRoleName());
		}
		return false;
	}

	@Produces
	public User getCurrentUser() {
		return currentUser;
	}

}
